import Types from '../types';
import {handleData, _projectModels, doCallBack} from '../ActionUtil';
import ArrayUtil from '../../util/ArrayUtil';
import Utils from '../../util/Utils';
const API_URL = 'https://api.github.com/search/repositories?q=';
const QUERY_STR = '&sort=stars';
const CANCEL_TOKENS = []; //点击取消次数
/**
 * 获取最热数据的异步action
 * @param inputKey 搜索关键字
 * @param token 与该搜索关联的唯一token,取消搜索
 * @param popularKeys 最热模块下的标签
 */
export function onSearch(
  inputKey,
  pageSize,
  token,
  favoriteDao,
  popularKeys,
  callBack,
) {
  return dispatch => {
    dispatch({type: Types.SEARCH_REFRESH});
    fetch(genFetchUrl(inputKey), {
      headers: {
        Accept:
          'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;',
        'Content-Type': 'text/plain;charset=UTF-8',
        'User-Agent':
          'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36',
      },
    })
      .then(response => {
        //取消异步操作任务,如果取消不做处理
        return hasCancel(token) ? null : response.json();
      })
      .then(responseData => {
        //取消异步操作任务,如果取消不做处理
        if (hasCancel(token, true)) {
          console.log('用户取消');
          return;
        }
        if (
          !responseData ||
          !responseData.items ||
          responseData.items.length === 0
        ) {
          dispatch({
            type: Types.SEARCH_FAIL,
            message: `没有找到${inputKey}的项目`,
          });
          doCallBack(callBack, `没有找到${inputKey}的项目`);
          return;
        }
        let items = responseData.items;
        handleData(
          Types.SEARCH_REFRESH_SUCCESS,
          dispatch,
          '',
          {data: items},
          pageSize,
          favoriteDao,
          {
            showBottomButton: !Utils.checkKeyIsExist(popularKeys, inputKey),
            inputKey,
          },
        );
      })
      .catch(e => {
        console.error(e);
        dispatch({
          type: Types.SEARCH_FAIL,
          error: e,
        });
      });
  };
}

/**
 * 取消一个异步任务
 * @param {*} token
 */
export function onSearchCancel(token) {
  return dispatch => {
    CANCEL_TOKENS.push(token);
    dispatch({
      type: Types.SEARCH_CANCEL,
    });
  };
}

/**
 * 加载更多
 * @param pageIndex 第几页
 * @param pageSize  每页展示条数
 * @param dataArray 原始数据
 * @param favoriteDao
 * @param callback 回调函数，可以通过回调函数来向调用页面通信：比如异常信息的展示，没有更多等待
 * @returns {function (*)}
 */
export function onLoadMoreSearch(
  pageIndex,
  pageSize,
  dataArray = [],
  favoriteDao,
  callback,
) {
  return dispatch => {
    setTimeout(() => {
      //模拟网络请求
      if ((pageIndex - 1) * pageSize >= dataArray.length) {
        //已经加载完全部数据
        if (typeof callback === 'function') {
          callback('no more');
        }
        dispatch({
          type: Types.SEARCH_LOAD_MORE_FAIL,
          error: 'no more',
          pageIndex: --pageIndex,
          // projectModes: dataArray,
        });
      } else {
        //本次可载入的最大数据量
        let max =
          pageSize * pageIndex > dataArray.length
            ? dataArray.length
            : pageSize * pageIndex;
        _projectModels(dataArray.slice(0, max), favoriteDao, data => {
          dispatch({
            type: Types.SEARCH_LOAD_MORE_SECCESS,
            pageIndex,
            projectModes: data,
          });
        });
      }
    }, 500);
  };
}

function genFetchUrl(key) {
  return API_URL + key + QUERY_STR;
}

/**
 * 检查指定token是否已经取消
 * @param token
 * @param isRemove
 * @returns {boolean}
 * includes 检测数组是否包含 token :
 */
function hasCancel(token, isRemove) {
  if (CANCEL_TOKENS.includes(token)) {
    isRemove && ArrayUtil.remove(CANCEL_TOKENS, token);
    return true;
  }
  return false;
}
